package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.pojos.WmUser;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.dtos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile==null||multipartFile.getSize()==0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null)
        {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(originalFilename)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        String fileId=null;
        String filename= UUID.randomUUID().toString().replaceAll("-","");
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            fileId=fileStorageService.store(prefix,(filename+suffix),multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"服务器繁忙请稍后重试");
        }

        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite+fileId);
        // 4 返回结果


        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId,user.getId());
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> pageReq=new Page(dto.getPage(),dto.getPage());
        IPage<WmMaterial> result = this.page(pageReq, wrapper);
        List<WmMaterial> lists = result.getRecords();
        for (WmMaterial list : lists) {
            list.setUrl(webSite+list.getUrl());
        }
        PageResponseResult pageResponseResult=new PageResponseResult(dto.getPage(),dto.getSize(),result.getTotal());
        pageResponseResult.setData(lists);

        return pageResponseResult;
    }
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count>0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        removeById(id);
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        if (!wmMaterial.getUserId().equals(user.getId())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }wmMaterial.setIsCollection(type);
        updateById(wmMaterial);
        return ResponseResult.okResult();

    }

    private boolean checkFileSuffix(String originalFilename) {
        if (StringUtils.isBlank(originalFilename)){
            return false;
        }
        List<String> lists = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow =false;
        for (String list : lists) {
            if (originalFilename.endsWith(list)){
                isAllow= true;
            }
        }
        return isAllow;
    }
}
